package com.gydz.interferencenetworkmanagement.common.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;


/*
* 配置服务处理器类
* */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) {
        ByteBuf byteBuf = null;
        if(DatagramPacket.class.equals(object.getClass())){    //udp传输接收
            DatagramPacket pa = (DatagramPacket)object;
            byteBuf = pa.content();
            String readStr = byteBuf.toString(Charset.forName("utf-8"));
            /*===========================此处写接收处理===========================*/

            /*=================================================================*/
            /*===========================此处写回复处理===========================*/
            // 回复数据到客户端
            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<root>"
                    + "<head>"
                    + "</head>"
                    + "<body>"
                    + "<resp>success</resp>"
                    + "</body>"
                    + "</root>";
            System.out.println(new Date() + ": 服务端写出数据 -> " +str);
            /*=================================================================*/

            ByteBuf out = getByteBuf(ctx,str);
            DatagramPacket sendPacket = new DatagramPacket(Unpooled.copiedBuffer(out), pa.sender());
            ctx.channel().writeAndFlush(sendPacket);

        }else {    //tcp传输接收
            byteBuf = (ByteBuf) object;
            System.out.println(new Date() + ": 服务端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));
            // 回复数据到客户端
            System.out.println(new Date() + ": 服务端写出数据");
            String str = "serverResp-test";
            ByteBuf out = getByteBuf(ctx,str);
            ctx.channel().writeAndFlush(out);
        }


    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx,String str) {
        byte[] bytes = str.getBytes(Charset.forName("utf-8"));
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes(bytes);
        return buffer;
    }
}
